<template>
  <div class="sys-platform" @click="bodyclick">
    <div class="pl-tools">
      <h1>{{stage.display.name}}</h1>
      <div class="pl-handle">
       <ul>
         <li @click="saveAndExit">
           <i class="iconfont">&#xe616;</i>
           保存
         </li>
         <li @click="saveAndPreview">
           <i class="iconfont">&#xe601;</i>
           保存并预览
         </li>
         <li @click="exit">
           <i class="iconfont">&#xe643;</i>
           直接退出
         </li>
       </ul>
      </div>
    </div>
    <div class="pl-components">
      <div class="pl-config-title" style="text-align:center;">新增</div>
      <ul class="pickchart" style="overflow: scroll;height: calc(100% - 40px);">
        <li @click="addChart(20)">
          <i class="iconfont">&#xe732;</i>
          文字
        </li>
        <li @click="addMap">
          <i class="iconfont">&#xe638;</i>
          地图
        </li>
        <li @click="addChart(2)">
          <i class="iconfont">&#xe701;</i>
          竖向柱
        </li>
        <li @click="addChart(10)">
          <i class="iconfont">&#xe6d0;</i>
          横向柱
        </li>
        <li @click="addChart(3)">
          <i class="iconfont">&#xe702;</i>
          折线图
        </li>
        <li @click="addChart(4)">
          <i class="iconfont">&#xe62a;</i>
          饼图
        </li>
        <li @click="addChart(1)">
          <i class="iconfont">&#xe600;</i>
          表格
        </li>
        <li @click="addChart(5)">
          <i class="iconfont">&#xe621;</i>
          全环形
        </li>
        <li @click="addChart(11)">
          <i class="iconfont">&#xe61f;</i>
          半环形
        </li>
        <li @click="addChart(6)">
          <i class="iconfont">&#xe669;</i>
          雷达图
        </li>
        <li @click="addChart(12)">
          <i class="iconfont">&#xe647;</i>
          热词
        </li>
      </ul>
    </div>
    <div class="pl-content">
      <div id="stage">
        <div id="stage-bg" :style="displaycss"></div>
        <div id="stage-grid"></div>
        <Chart v-for="chart in charts"
          :key="chart.id"
          :color="stage.display.globalColor"
          :component="chart"
          :grid="stage.grid"
          :bsId="bsId"
          :scale="scale"
          :handleActive="handleActive"
          @remove="handleRemove"></Chart>
      </div>
    </div>
    <div class="pl-config">
      <div class="pl-config-title">控制面板</div>
      <component v-bind:is="currentConfigComponent"
        @saveConfig="handleSaveConfig"
        @saveDrill="handleSaveDrill"
        :datasource="datasource"
        :drillsource="drillsource"
        @drill="handleRemoteDrill"
        @handleUpdateDisplay="onlyHandleUpdateDisplay"
        @handleUpdateDisplayImg="handleUpdateDisplayImg"
        @remote="handleRemoteDataSource"
        @remove="handleRemove"
        :component="active.bsChartInfo ? active: stage">
      </component>
    </div>
    <el-dialog title="请选择地区" :visible.sync="mapForm.show" width="600px">
      <el-form :model="mapForm">
        <el-form-item label="地区" :label-width="'100px'">
          <el-select v-model="mapForm.code" filterable placeholder="请选择">
            <el-option
              v-for="item in allmap"
              :key="item.adcode"
              :label="item.name"
              :value="item.adcode">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="mapForm.show = false">取 消</el-button>
        <el-button type="primary" @click="addChart(7)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Services from '@/services/'
import Chart from '@/page/components/chart'
import { mapState, mapActions, mapMutations } from 'vuex';

export default {
  components: { Chart },
  data(){
    return{
      bsId: 0,
      active: {},
      scale: 1,
      datasource: [],
      drillsource: [],
      stage: {
        width: 1920,
        height: 1080,
        scale: 1,
        grid: 10,
        display: {}
        // globalColor: ''
      },
      mapForm: {
        show: false,
        code: null,
      },
      allmap: [{"adcode":320100,"name":"南京市"},{"adcode":320200,"name":"无锡市"},{"adcode":320300,"name":"徐州市"},{"adcode":320400,"name":"常州市"},{"adcode":320500,"name":"苏州市"},{"adcode":320600,"name":"南通市"},{"adcode":320700,"name":"连云港市"},{"adcode":320800,"name":"淮安市"},{"adcode":320900,"name":"盐城市"},{"adcode":321000,"name":"扬州市"},{"adcode":321100,"name":"镇江市"},{"adcode":321200,"name":"泰州市"},{"adcode":321300,"name":"宿迁市"}]}
  },
  computed: {
    ...mapState({
      charts: state => state.charts.list,
    }),
    currentConfigComponent(){
      let chartType = 'BaseConfig'
      console.log(this.active.bsChartComponent)
      if(this.active.bsChartComponent){
        switch(this.active.bsChartComponent.chartType){
          case 1: chartType = 'TableConfig'; break;
          case 2: chartType = 'BarConfig'; break;
          case 3: chartType = 'LineConfig'; break;
          case 4: chartType = 'CircleConfig'; break;
          case 5: chartType = 'PieConfig'; break;
          case 6: chartType = 'RadarConfig'; break;
          case 7: chartType = 'MapConfig'; break;
          case 10: chartType = 'CbarConfig'; break;
          case 11: chartType = 'Pie2Config'; break;
          case 12: chartType = 'HotsConfig'; break;
          case 20: chartType = 'WordConfig'; break;
        }
      }
      return chartType
    },
    displaycss(){
      return {
        background : this.stage.display.backImg ? "url('" + this.stage.display.backImg + "')" : '#fff'
      }
      
    }
  },
  mounted(){
    const stage = document.getElementById('stage')
    const parentNode = stage.parentNode
    let height = parentNode.offsetHeight;
    let width = parentNode.offsetWidth;
    const ratio = 1920/1080
    let nw = 0, nh = 0;
    if(width/height > ratio){
      nw = width/ratio
      nh = height
    } else {
      nw = width
      nh = height/ratio
    }
    this.scale = nw / 1920
    stage.style.transform = "scale(" + this.scale + "," + this.scale + ")";
    document.getElementById('stage-grid').style.backgroundSize = this.stage.grid + 'px ' + this.stage.grid + 'px,' + this.stage.grid + 'px ' + this.stage.grid + 'px';
  },
  created(){
    // this.stage.display = this.$route.params
    this.bsId = parseInt(this.$route.params.id)
    this.init()
  },
  methods:{
    ...mapActions({
      CHARTS_LIST: 'charts/LIST',
    }),
    ...mapMutations({
      CHARTS_ADD: 'charts/ADD'
    }),
    init(){
      this.CHARTS_LIST({
        bsId: this.bsId
      })
      Services.DISPLAYS_GET({
        id: this.bsId
      }).then(res => {
        this.stage.display = res
        // this.stage.globalColor = res.globalColor
      })
    },
    bodyclick(e){
      if(e.target.id === 'stage' || e.target.id === 'stage-grid') {
        this.active = {}
      }
    },
    handleActive(component){
      this.active = component
    },
    // 添加地图
    addMap(){
      this.mapForm.show = true
    },
    // 添加图表
    addChart(type){
      if(type == 7 && !this.mapForm.code){
        return null
      }
      let chartdefault = {
        name: '',
        descMsg: '',
        width: 400,
        height: 300,
        isAutoheight: 0,
        x: 20,
        y: 20,
        refreshTime: 0,
        bsInfoId: this.bsId,
        chartType: 0
      }
      switch(type) {
        case 1 : chartdefault = {
          ...chartdefault,
          name: '表格',
          chartType: 1,
        }; break;
        case 2 : chartdefault = {
          ...chartdefault,
          name: '柱状',
          chartType: 2,
        }; break;
        case 10 : chartdefault = {
          ...chartdefault,
          name: '横柱状',
          chartType: 10,
        }; break;
        case 3 : chartdefault = {
          ...chartdefault,
          name: '折线',
          chartType: 3,
        }; break;
        case 4 : chartdefault = {
          ...chartdefault,
          name: '饼图',
          chartType: 4,
        }; break;
        case 5 : chartdefault = {
          ...chartdefault,
          name: '环形',
          chartType: 5,
        }; break;
        case 11 : chartdefault = {
          ...chartdefault,
          name: '半环形',
          chartType: 11,
        }; break;
        case 6 : chartdefault = {
          ...chartdefault,
          name: '雷达',
          chartType: 6,
        }; break;
        case 7 : chartdefault = {
          ...chartdefault,
          name: '地图',
          chartType: 7,
          chartConfigJson:{
            adcode:this.mapForm.code,
            mapJson: this.mapForm.code,
            name: "name",
            lat: "lat",
            lng: "lng",
            value: "data_value",
            area:"MAPS",
          },
          chartConfig: "",
        }; 
        chartdefault.chartConfig = JSON.stringify(chartdefault.chartConfigJson)
        break;
        case 8 : chartdefault = {
          ...chartdefault,
          name: '仪表盘',
          chartType: 8,
        }; break;
        case 12: chartdefault = {
          ...chartdefault,
          name: '热词',
          chartType: 12,
        }; break;
        case 20 :
          const fontSize = 28
          let wordInfo = {
            word: "请输入文字", 
            css: {
              color: '#333',
              fontSize: fontSize
            }
          }
          chartdefault = {
            ...chartdefault,
            name: '文字',
            chartType: 20,
            width: Math.ceil(wordInfo.word.length * fontSize * 1.2),
            height: Math.ceil(fontSize * 1.7),
            wordInfo: JSON.stringify(wordInfo)
          }; break;
      }
      Services.CHARTS_ADD(chartdefault).then(res => {
        if(res.code === 0){
          this.mapForm.show = false
          this.CHARTS_ADD(res.data)
        }
      })
    },
    //格式化数据 提交服务器
    formatChartData(component){
      let bsChart = {
        id: component.bsChartInfo.id,
        "bsChartInfoRequest.name" : component.bsChartInfo.name,
        "bsChartComponentRequest.bindDataType": component.bsChartComponent.bindDataType,
        "bsChartComponentRequest.bindDataId" : component.bsChartComponent.bindDataId,
        "bsChartComponentRequest.isDrill" :  component.bsChartComponent.isDrill,
        "bsChartComponentRequest.drillParams" : component.bsChartComponent.drillParams,
        "bsChartComponentRequest.drillChartId" : component.bsChartComponent.drillChartId,
        "bsChartComponentRequest.chartConfig" :  component.bsChartComponent.chartConfig,
        "bsChartComponentRequest.title" : component.bsChartComponent.title,
        "bsChartInfoRequest.name" : component.bsChartInfo.name,
        "bsChartInfoRequest.descMsg" : component.bsChartInfo.descMsg,
        "bsChartInfoRequest.width" : component.bsChartInfo.width,
        "bsChartInfoRequest.height" : component.bsChartInfo.height,
        "bsChartInfoRequest.isAutoheight" : component.bsChartInfo.isAutoheight,
        "bsChartInfoRequest.x" : component.bsChartInfo.x,
        "bsChartInfoRequest.y" : component.bsChartInfo.y,
        "bsChartInfoRequest.refreshTime" : component.bsChartInfo.refreshTime,
        "bsChartInfoRequest.bsInfoId" : component.bsChartInfo.bsInfoId,
        "bsChartInfoRequest.wordInfo" : component.bsChartInfo.wordInfoJSON ? JSON.stringify(component.bsChartInfo.wordInfoJSON) : component.bsChartInfo.wordInfo,
      }
      return bsChart
    },
    // chartConfig
    handleSaveConfig(id, chartConfig) {
      this.charts.forEach((component, index) => {
        if(id === component.bsChartInfo.id){
          let componentClone = Object.assign({}, component)
          if(chartConfig){
            componentClone.bsChartComponent.chartConfig = chartConfig
          }
          const requestBody = this.formatChartData(componentClone)
          this.handleSubmit(requestBody)
        }
      })
    },
    // Drill
    handleSaveDrill(id, drill) {
      this.charts.forEach((component, index) => {
        if(id === component.bsChartInfo.id){
          let componentClone = Object.assign({}, component)
          if(drill){
            componentClone.bsChartComponent.drillParams = drill
          }
          const requestBody = this.formatChartData(componentClone)
          this.handleSubmit(requestBody)
        }
      })
    },
    // 保存 当前激活图标
    handleSubmit(requestBody){
      Services.CHARTS_UPDATE(requestBody).then(res => {
        if(res.code === 0){
          this.$message({
            message: "更新成功",
            type: "success"
          })
        }
      })
    },
    // 删除组件
    handleRemove(id){
      this.$confirm("此操作将永久删除该组件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        Services.CHARTS_REMOVE({
          id : id
        }).then(res => {
          if(res.code === 0){
            window.location.reload()
          }
        })
      })
    },
    //远程选择 数据源
    handleRemoteDataSource(e, component){
      if(component.bsChartComponent.bindDataType == 1){
        Services.SQL_LIST({
          name: e,
          page: 1,
          size: 10
        }).then(res => {
          this.datasource = res.rows
        })
      } else {
        Services.API_LIST({
          name: e,
          page: 1,
          size: 10
        }).then(res => {
          this.datasource = res.rows
        })
      }
    },
    // 远程选择 下钻数据
    handleRemoteDrill(e){
      Services.DRILL_LIST({
        name: e,
        page: 1,
        size: 10
      }).then(res => {
        console.log(res.rows)
        this.drillsource = res.rows
      })
    },
    saveAll(){
      let saveList = []
      this.charts.forEach(chart => {
        saveList.push(this.formatChartData(chart))
      })
      return saveList
    },
    saveAsTemplate(){
      this.handleUpdateDisplay()
      Services.DISPLAYS_SAVE_TEMPLATE({
        jsonData: JSON.stringify(this.charts)
      }).then(res => {
        if(res.code == 0){
          this.$message.success('模板保存成功')
        } else {
          this.$message.error(res.msg || '模板保存失败')
        }
      })
      
    },
    saveAndPreview(){
      this.handleUpdateDisplay()
      Services.DISPLAYS_SAVEALL({
        jsonData: JSON.stringify(this.charts),
        isRelease: 1
      }).then(res => {
        let routeUrl = this.$router.resolve({
          name: "displaysPreview",
          params: {
            id: this.stage.display.releaseId
          }
        });
        window.open(routeUrl.href, "_blank")
      })
    },
    saveAndExit(){
      this.handleUpdateDisplay()
      Services.DISPLAYS_SAVEALL({
        jsonData: JSON.stringify(this.charts),
        isRelease: 0
      }).then(() => {
        this.$message({
          message: "更新成功",
          type: "success",
          onClose: function(){
            window.location.reload()
          }
        })
        
        // this.$router.back(-1)
      })
    },
    exit(){
      this.$confirm("确定不做任何保存直接退出?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$router.back(-1)
      })
      
    },
    onlyHandleUpdateDisplay(display){
      this.handleUpdateDisplay(display)
      setTimeout(function(){
        window.location.reload()
      }, 500)
    },
    // 更新大屏基础组件
    handleUpdateDisplay(display){
      Services.DISPLAYS_EDIT(this.stage.display).then(res => {
        if(res.code === 0){
          this.$message({
            message: "更新成功",
            type: "success"
          })
        }
      })
    },
    handleUpdateDisplayImg(path){
      this.stage.display.backImg = path
    }
  }
}
</script>
<style lang="less">
  .sys-platform{
    padding-top: 60px;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    .pl-tools{
      top: 0;
      width: 100%;
      height: 60px;
      position: absolute;
      padding: 0 20px;
      background: #1c2b36;
      color: #fff;
      box-sizing: border-box;
      h1{
        margin: 0;
        padding: 0;
        font-weight: 200;
        line-height: 60px;
        float: left;
        font-size: 24px;
      }
      .pl-handle{
        float: right;
        ul{
          li{
            display: inline-block;
            text-align: center;
            border-right: 1px solid #3f4448;
            width: 120px;
            margin-top: 10px;
            font-size: 12px;
            cursor: pointer;
            i.iconfont{
              font-size: 20px;
              display: block;
            }
            &:last-child{
              border-right: 0;
            }
          }
        }
      }
    }
    .pl-components{
      float: left;
      width: 100px;
      height: 100%;
      background: #fff;
      border-right: 2px solid #ccc;
      .pickchart{
        li{
          text-align: center;
          font-size: 12px;
          color: #333;
          border: 1px solid #ccc;
          margin: 10px;
          padding: 10px;
          box-sizing: border-box;
          cursor: pointer;
          background: #fff;
          i.iconfont{
            font-size: 24px;
            display: block;
            color: #333;
            margin-bottom: 4px;
          }
          &:hover{
            box-shadow: 0 0 4px 1px rgba(0, 0, 0, 0.1);
            color: #aaa;
          }
        }
      }
    }
    .pl-content{
      margin-left: 120px;
      margin-right: 320px;
      height: 100%;
      position: relative;
      box-sizing: border-box;
      z-index: 10;
      padding-top: 20px;
      #stage{
        width: 1920px;
        height: 1080px;
        transform-origin: 0 0;
        box-shadow: 0 0 10px 2px rgba(0,0,0,.4);
      }
    }
    #stage-bg{
      width: 100%;
      height: 100%;
      position: absolute;
      background-size: 100% 100%;
      // opacity: .4;
      top: 0;
      left: 0;
    }
    #stage-grid{
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-color: rgba(30, 30, 30, 0);
      background-origin: padding-box, padding-box;
      box-sizing: border-box;
      background-image: linear-gradient(-90deg, rgba(30, 30, 30, .1) 1px, transparent 1px), linear-gradient(rgba(30, 30, 30, 0.1) 1px, transparent 1px);
    }
    .pl-config{
      border-left: 2px solid #ccc;
      position: absolute;
      right: 0;
      top: 60px;
      width: 300px;
      height: calc(100% - 60px);
      background: #fff;
      box-sizing: border-box;
    }
    .pl-config-title{
      background: #f2f2f2;
      line-height: 40px;
      padding: 0 20px;
    }
  }
  .configtab{
    .el-tabs__content{
      padding: 0 10px;
      .el-form-item--small{
        .el-form-item__label{
          line-height: 22px;
          padding-bottom: 5px;
        }
      }
    }
  }
  .el-tabs__nav-scroll{
    padding-left: 40px;
  }
  
</style>
